package io.gitee.yxsnake.embark.web.core.exception;

import io.gitee.yxsnake.embark.web.core.base.ErrorCode;
import io.gitee.yxsnake.embark.web.core.base.IResultCode;
import io.gitee.yxsnake.embark.web.core.base.Result;
import io.gitee.yxsnake.embark.web.core.context.TrackContext;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.io.Serial;

/**
 * @author snake
 * @description 1.对于具体的业务异常继承此异常来实现，例如登录失败返回code码异常，则定义LoginFailException
 * 2.如果异常需要被外部服务感知到则进行抛出，否则内部拦截处理
 * @since 2024/9/28 23:46
 */

@Data
@ToString
@EqualsAndHashCode(callSuper = true)
public class BizException extends RuntimeException {


    @Serial
    private static final long serialVersionUID = 430933593095358673L;

    public ErrorCode errorCode;

    public BizException(ErrorCode errorCode) {
        super(errorCode.getMsg());
        this.errorCode = errorCode;
    }

    public BizException(String message) {
        super(message);
        this.errorCode = ErrorCode.builder()
                .code(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
                .msg(message)
                .build();
    }

    public BizException(Integer code, String message) {
        ErrorCode errorCode = ErrorCode.builder()
                .code(code)
                .msg(message)
                .build();
        this.errorCode = errorCode;
    }

    public BizException(String message, Throwable cause) {
        super(message, cause);
    }

    public BizException(Throwable cause) {
        super(cause);
    }

    public Result getResult() {
        return Result.builder()
                .code(this.errorCode.getCode())
                .msg(this.errorCode.getMsg())
                .trackId(TrackContext.getTrackId())
                .build();
    }

    public BizException(IResultCode resultCode) {
        super(resultCode.getMsg());
        this.errorCode = ErrorCode.builder()
                .code(resultCode.getCode())
                .msg(resultCode.getMsg())
                .build();
    }
}

